package com.ibeeking.gmc.global.g.rest.service.impl;

import com.ibeeking.gmc.global.g.rest.service.IJobCreateService;
import com.ibeeking.found.common.constants.UserConstant;
import com.ibeeking.found.common.entity.TimeTaskDTO;
import com.ibeeking.found.common.entity.TimeTaskJobParam;

import com.ibeeking.gmc.global.g.rest.service.ITimeTaskService;
import com.ibeeking.gmc.job.core.enums.ExecutorBlockStrategyEnum;
import com.ibeeking.gmc.job.core.enums.RouteStrategyEnum;
import com.ibeeking.gmc.job.core.glue.GlueTypeEnum;
import com.ibeeking.found.job.model.BaseJobModel;
import com.ibeeking.found.job.model.JobInfoModel;
import com.ibeeking.found.job.service.IJobService;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.Future;

/**
 * @ClassName InventoryJobCreateServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2021-02-05 10:13
 **/
@Service
public class JobCreateServiceImpl implements IJobCreateService {

    private static final Logger log = LoggerFactory.getLogger(JobCreateServiceImpl.class);

    @Resource
    private IJobService jobServiceImpl;

    @Resource
    private ITimeTaskService timeTaskServiceImpl;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createJobInfo(Integer tenantId, JobInfoModel model){
        //开始创建/修改任务
        Future<ResponseResult<Boolean>> job = jobServiceImpl.createJob(model);
        //获取任务创建/修改结果
        try {
            ResponseResult<Boolean> responseResult = job.get();
            return responseResult.getData();
        } catch (Exception e) {
            LogUtils.error("租户[{}]定时任务创建失败", tenantId, e);
            return false;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean delJobInfo(Integer tenantId, JobInfoModel model){
        Future<ResponseResult<Boolean>> job = jobServiceImpl.delJob(model);
        try {
            ResponseResult<Boolean> responseResult = job.get();
            return responseResult.getData();
        } catch (Exception e) {
            LogUtils.error("租户[{}]定时任务删除失败", tenantId, e);
            return false;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean createJobInfoForTenantDataSync(TimeTaskJobParam param){
        //构建任务体
        LogUtils.info(">>>>>>> Begin Create TenantDataSync:{}", JsonUtils.toJsonStr(param));
        Integer tenantId = param.getTenantId();
        String industry = param.getIndustry();
        String handler = param.getHandler();
        TimeTaskDTO timeTask= timeTaskServiceImpl.queryTimeTaskByIndustryAndHandler(industry, handler);
        if(timeTask == null) return false;
        JobInfoModel model = new JobInfoModel();
        model.setBusinessKey(tenantId.toString());
        model.setJobName(tenantId.toString().concat("_").concat(timeTask.getJobName()));
        model.setType(timeTask.getJobType());
        model.setJobCron(timeTask.getJobCron());
        model.setJobDesc(timeTask.getRemark());
        model.setAuthor(UserConstant.SYSTEM_ADMIN);
        model.setRouteStrategyEnum(RouteStrategyEnum.ROUND);
        model.setExecutorHandler(timeTask.getExecutorHandler());
        model.setExecutorParam(timeTask.getExecutorParam());
        model.setExecutorBlockStrategyEnum(ExecutorBlockStrategyEnum.SERIAL_EXECUTION);
        model.setExecutorTimeout(timeTask.getExecutorTimeout());
        model.setExecutorFailRetryCount(timeTask.getExecutorFailRetryCount());
        model.setGlueTypeEnum(GlueTypeEnum.BEAN);
        model.setTriggerStatus(timeTask.getTriggerStatus());
        //开始创建/修改任务
        Future<ResponseResult<Boolean>> job = jobServiceImpl.createJob(model);
        //获取任务创建/修改结果
        try {
            ResponseResult<Boolean> responseResult = job.get();
            return responseResult.getData();
        } catch (Exception e) {
            LogUtils.error("租户[{}]数据发布定时任务创建失败", tenantId, e);
            return false;
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean delJobInfoForTenantDataSync(TimeTaskJobParam param){
        //删除定时任务
        LogUtils.info(">>>>>>> Begin Delate TenantDataSync:{}", JsonUtils.toJsonStr(param));
        Integer tenantId = param.getTenantId();
        String industry = param.getIndustry();
        String handler = param.getHandler();
        TimeTaskDTO timeTask= timeTaskServiceImpl.queryTimeTaskByIndustryAndHandler(industry, handler);
        if(timeTask == null) return false;
        BaseJobModel jobModel = new BaseJobModel();
        jobModel.setBusinessKey(String.valueOf(tenantId));
        jobModel.setExecutorHandler(timeTask.getExecutorHandler());
        jobModel.setType(timeTask.getJobType());
        Future<ResponseResult<Boolean>> job = jobServiceImpl.delJob(jobModel);
        try {
            ResponseResult<Boolean> responseResult = job.get();
            return responseResult.getData();
        } catch (Exception e) {
            LogUtils.error("{}_库存概览统计定时任务删除失败", tenantId, e);
            return false;
        }
    }

}
